package com.promote.hotspot.server.netty.dashboard;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.java.Log;
import org.promote.hotspot.common.model.HotSpotMsg;
import org.promote.hotspot.common.model.MessageType;
import org.promote.hotspot.common.model.MsgBuilder;
import org.promote.hotspot.common.tool.Constant;
import org.promote.hotspot.common.tool.FastJsonUtils;

/**
 * @author enping.jep
 * @date 2024/02/21 14:24
 **/
@Log
@ChannelHandler.Sharable
public class NettyClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("channelActive:" + ctx.name());
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        NettyClient.getInstance().disConnect();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;

            if (idleStateEvent.state() == IdleState.ALL_IDLE) {
                //向服务端发送消息
                ctx.writeAndFlush(MsgBuilder.buildByteBuf(new HotSpotMsg(MessageType.PING, Constant.PING)));
            }
        }

        super.userEventTriggered(ctx, evt);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
        HotSpotMsg msg = FastJsonUtils.toBean(message, HotSpotMsg.class);
        if (MessageType.PONG == msg.getMessageType()) {
            log.info("heart beat");
        }
    }
}
